<template>
  <div class="course-management-container">
    <el-page-header @back="goBack">
      <template #content>
        <div class="header-content">
          <span class="header-title">课程管理 - {{ classInfo.className || '加载中...' }}</span>
          <el-tag v-if="classInfo.classCode" type="info">
            班级代码: {{ classInfo.classCode }}
          </el-tag>
        </div>
      </template>
    </el-page-header>
    
    <el-card class="courses-card">
      <div class="action-bar">
        <el-button 
          type="primary" 
          @click="showAddCourseDialog"
          :icon="Plus"
          :loading="loading"
        >
          添加课程
        </el-button>
        <el-button 
          type="info" 
          @click="loadData"
          :icon="Refresh"
          :loading="loading"
        >
          刷新数据
        </el-button>
        
        <div class="view-toggle">
          <el-tooltip content="卡片视图" placement="top">
            <el-button 
              :type="viewMode === 'card' ? 'primary' : ''" 
              @click="viewMode = 'card'"
              :icon="Grid"
            />
          </el-tooltip>
          <el-tooltip content="列表视图" placement="top">
            <el-button 
              :type="viewMode === 'list' ? 'primary' : ''" 
              @click="viewMode = 'list'"
              :icon="List"
            />
          </el-tooltip>
        </div>
      </div>
      
      <!-- 卡片视图 -->
      <div class="card-view" v-if="viewMode === 'card'" v-loading="loading">
        <el-row :gutter="20">
          <el-col 
            v-for="course in processedCourses" 
            :key="course.id" 
            :xs="24" :sm="12" :md="8" :lg="6"
          >
            <el-card class="course-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="course-name">{{ course.name }}</span>
                  <el-tag :type="course.status === 1 ? 'success' : 'warning'" size="small">
                    {{ courseStatusMap[course.status] || '未知状态' }}
                  </el-tag>
                </div>
              </template>
              
              <div class="course-info">
                <div class="info-item">
                  <span class="label">课程ID:</span>
                  <span>{{ course.id }}</span>
                </div>
                <div class="info-item">
                  <span class="label">创建时间:</span>
                  <span>{{ formatDate(course.createTime) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">简介:</span>
                  <span class="course-intro">{{ course.introduction || '暂无简介' }}</span>
                </div>
              </div>
              
              <div class="card-actions">
                <el-tooltip content="移除课程" placement="top">
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click.stop="removeCourse(course.id)"
                    :icon="Delete"
                  />
                </el-tooltip>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-empty v-if="!loading && processedCourses.length === 0" description="暂无课程数据"/>
      </div>
      
      <!-- 列表视图 -->
      <div class="list-view" v-else v-loading="loading">
        <el-table :data="processedCourses" border style="width: 100%">
          <el-table-column prop="name" label="课程名称" width="180" />
          <el-table-column prop="id" label="课程ID" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="introduction" label="课程简介" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'warning'">
                {{ courseStatusMap[row.status] || '未知状态' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-tooltip content="移除课程" placement="top">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click.stop="removeCourse(row.id)"
                  :icon="Delete"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 添加课程对话框 -->
    <!-- 添加课程对话框部分 -->
<el-dialog 
  v-model="showCourseDialog" 
  title="添加课程到班级" 
  width="50%"
  :close-on-click-modal="false"
>
  <div v-loading="dialogLoading" class="course-select-dialog">
    <el-alert
      v-if="availableCourses.length === 0 && !dialogLoading"
      title="没有可添加的课程，请先创建课程"
      type="warning"
      show-icon
      class="mb-4"
    />
    
    <el-select 
      v-model="selectedCourseId" 
      placeholder="请选择课程" 
      filterable
      style="width: 100%"
      clearable
      :disabled="availableCourses.length === 0"
    >
      <el-option
        v-for="course in availableCourses"
        :key="course.id"
        :label="course.name || course.couName || `课程${course.id}`"
        :value="course.id"
      />
    </el-select>
    
    <div class="dialog-footer" style="margin-top: 20px; text-align: right">
      <el-button @click="showCourseDialog = false">取消</el-button>
      <el-button 
        type="primary" 
        @click="confirmAddCourse"
        :disabled="!selectedCourseId || dialogLoading"
        :loading="dialogLoading"
      >
        确认添加
      </el-button>
    </div>
  </div>
</el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { 
  Plus, Delete, Refresh, Grid, List
} from '@element-plus/icons-vue'
import { 
  ElMessage, 
  ElMessageBox
} from 'element-plus'
import { classApi } from '@/api/class'
import { teacherApi } from '@/api/teacher'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const dialogLoading = ref(false)
const classInfo = ref({})
const rawCourses = ref([])
const showCourseDialog = ref(false)
const selectedCourseId = ref(null)
const availableCourses = ref([])
const viewMode = ref('card')

// 课程状态映射
const courseStatusMap = {
  0: '未发布',
  1: '已发布',
  2: '已下架'
}

// 处理后的课程数据
const processedCourses = computed(() => {
  // 去重处理
  const uniqueCourses = []
  const courseIds = new Set()
  
  rawCourses.value.forEach(course => {
    if (!courseIds.has(course.id)) {
      courseIds.add(course.id)
      uniqueCourses.push({
        id: course.id,
        name: course.name,
        introduction: course.introduction,
        createTime: course.createTime,
        status: course.status
      })
    }
  })
  
  return uniqueCourses
})

// 格式化日期
const formatDate = (dateString) => {
  return dateString ? dayjs(dateString).format('YYYY-MM-DD HH:mm') : '未知时间'
}

// 获取教师ID
const getTeacherId = async () => {
  try {
    const userId = authStore.userId
    if (!userId) {
      throw new Error('用户未登录')
    }
    const response = await teacherApi.getTeacherByUid(userId)
    return response.id || response.data?.id
  } catch (error) {
    console.error('获取教师ID失败:', error)
    ElMessage.error('获取教师信息失败')
    return null
  }
}

// 加载班级信息
const loadClassInfo = async () => {
  try {
    const response = await classApi.getClassDetail(route.params.classId)
    classInfo.value = response.data || response
  } catch (error) {
    console.error('加载班级信息失败:', error)
    ElMessage.error('加载班级信息失败')
    classInfo.value = {}
  }
}

// 加载班级课程（优化后的版本）
const loadClassCourses = async () => {
  try {
    loading.value = true;
    const teacherId = await getTeacherId();
    if (!teacherId) throw new Error('无法获取教师ID');
    
    // 获取班级详情
    const response = await teacherApi.getClassDetail(teacherId, route.params.classId);
    const classData = response.data || response;
    
    console.log('完整班级数据:', classData);

    // 直接从顶层courses字段获取课程数据
    if (classData.courses && Array.isArray(classData.courses)) {
      // 去重处理
      const uniqueCourses = [];
      const courseIds = new Set();
      
      classData.courses.forEach(course => {
        if (!courseIds.has(course.id)) {
          courseIds.add(course.id);
          uniqueCourses.push({
            id: course.id,
            name: course.couName || `课程${course.id}`,
            introduction: course.couIntroduction || '',
            createTime: course.createTime,
            status: 1 // 默认设置为已发布状态
          });
        }
      });
      
      rawCourses.value = uniqueCourses;
      
      if (uniqueCourses.length === 0) {
        ElMessage.warning('该班级暂无有效课程数据');
      }
    } else {
      rawCourses.value = [];
      console.warn('班级中没有找到课程数据');
      ElMessage.warning('该班级暂无关联课程');
    }
  } catch (error) {
    console.error('加载课程列表失败:', error);
    ElMessage.error('加载课程列表失败: ' + error.message);
    rawCourses.value = [];
  } finally {
    loading.value = false;
  }
};

// 加载教师可添加的课程
const loadAvailableCourses = async () => {
  try {
    dialogLoading.value = true;
    const teacherId = await getTeacherId();
    if (!teacherId) throw new Error('无法获取教师ID');
    
    const response = await teacherApi.getTeacherCourses(teacherId);
    const allCourses = Array.isArray(response.data) ? response.data : 
                     Array.isArray(response) ? response : [];
    
    // 确保课程名称字段正确映射
    availableCourses.value = allCourses.map(course => ({
      id: course.id,
      name: course.name || course.couName, // 兼容两种可能的字段名
      // 其他需要的字段...
    }));
    
    // 过滤掉已存在的课程
    const currentCourseIds = new Set(rawCourses.value.map(c => c.id));
    availableCourses.value = availableCourses.value.filter(
      course => !currentCourseIds.has(course.id)
    );
    
  } catch (error) {
    console.error('加载可选课程失败:', error);
    ElMessage.error('加载可选课程失败: ' + error.message);
    availableCourses.value = [];
  } finally {
    dialogLoading.value = false;
  }
};

// 显示添加课程对话框
const showAddCourseDialog = async () => {
  await loadAvailableCourses()
  showCourseDialog.value = true
}

// 确认添加课程
const confirmAddCourse = async () => {
  if (!selectedCourseId.value) {
    ElMessage.warning('请选择要添加的课程')
    return
  }

  try {
    dialogLoading.value = true
    await teacherApi.addCourseToClass(
      route.params.classId, 
      selectedCourseId.value
    )
    ElMessage.success('课程添加成功')
    showCourseDialog.value = false
    selectedCourseId.value = null
    await loadData()
  } catch (error) {
    console.error('添加课程失败:', error)
    ElMessage.error(error.response?.data?.message || '添加课程失败')
  } finally {
    dialogLoading.value = false
  }
}

// 移除课程
const removeCourse = async (courseId) => {
  try {
    await ElMessageBox.confirm('确定要移除该课程吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    await classApi.removeCourseFromClass(
      route.params.classId, 
      courseId
    )
    
    // 本地更新课程列表
    rawCourses.value = rawCourses.value.filter(course => course.id !== courseId)
    
    ElMessage.success('课程移除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除课程失败:', error)
      ElMessage.error('移除课程失败')
    }
  } finally {
    loading.value = false
  }
}

// 加载所有数据
const loadData = async () => {
  loading.value = true
  try {
    await Promise.all([
      loadClassInfo(),
      loadClassCourses()
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 初始化加载
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.course-management-container {
  padding: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.view-toggle {
  display: flex;
  gap: 5px;
  margin-left: 10px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.view-toggle .el-button {
  border-radius: 0;
  border: none;
}

.courses-card {
  margin-top: 20px;
}

.card-view {
  min-height: 300px;
}

.list-view {
  min-height: 300px;
}

.course-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.course-name {
  font-size: 16px;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex-grow: 1;
}

.course-info {
  font-size: 14px;
  margin-bottom: 10px;
  flex-grow: 1;
}

.info-item {
  margin-bottom: 8px;
  display: flex;
}

.info-item .label {
  color: #606266;
  margin-right: 8px;
  width: 80px;
  font-weight: 500;
}

.course-intro {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 10px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>